package com.treeroot.springbootwithelastic.com.treeroot.es.tools;

import com.treeroot.springbootwithelastic.com.treeroot.es.entity.Product;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * @author treeRoot
 */
public class JdHtmlParsesTools {
    /**
     * 从京东爬虫---->解析数据
     *
     * @param keyword 关键字
     * @return 商品信息
     * @throws Exception 异常
     */
    public static List<Product> parseJd(String keyword) throws Exception {
        String path = "https://search.jd.com/Search?keyword=" + keyword;
        //Document整个网页对象
        Jsoup.connect(path).get();
        URL url = new URL(path);
        Document document = Jsoup.parse(url, 30000);
        Element jGoodsList = document.getElementById("J_goodsList");
        Elements li = jGoodsList.getElementsByTag("li");
        List<Product> list = new ArrayList<>();
        for (Element element : li) {
            //爬取商品价格
            String pprice = element.getElementsByClass("p-price").eq(0).text();
            //爬取商品信息
            String pname = element.getElementsByClass("p-name").eq(0).text();
            //爬取商品图片地址
            String img = element.getElementsByTag("img").eq(0).attr("data-lazy-img");
            list.add(new Product(pname, pprice, img));
        }
        return list;
    }

}
